import { expect } from '@jest/globals';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};
const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'project',
    product: 'default2',
    tasks: 'assembleApp',
  });

  const buffer = await fsExtra.readFile(path.resolve(projectRootPath, 'build-profile.json5'));
  const parse = JSON5.parse(buffer.toString());
  parse.app.products.push(
    {
      'name': 'default2',
      'signingConfig': 'default',
      'compatibleSdkVersion': '5.0.2(14)',
      'runtimeOS': 'HarmonyOS',
    }
  );
  parse.modules.forEach((module: { targets: { name: string; applyToProducts: string[]; }[]; }) => {
    const find = module.targets.find(target => target.name === 'default');
    if (find) {
      find.applyToProducts = ['default2'];
    }
  });
  await fsExtra.writeFile(path.resolve(projectRootPath, 'build-profile.json5'), JSON5.stringify(parse, null, 2));
  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行./hvigorw assembleApp -p product=default2', result);
  expect(result.stdout).toContain('Finished ::PackageApp.');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 判断构建成功的包名带default2
  // eslint-disable-next-line max-len
  const isDefault2 = await fsExtra.pathExists(path.resolve(projectRootPath, 'build/outputs/default2/myapplication-default2-unsigned.app'));
  expect(isDefault2).toBe(true);
};


TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_productApp_05_004')
  .description('命令行直接执行product打App包_短命令')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
